'''
Created on Mar 8, 2010

@author: Nick Heiner
'''
from models import Item, InCart
from google.appengine.api import memcache

# Adds one item to the cart
class AddToCart():
    """ Adds items to a cart """
    
    def __init__(self, CSIN, quantity, user):
        self.CSIN = CSIN
        self.quantity = quantity
        self.user = user
    
    def add(self, anon_timeout=None):
        """ Adds the items to the cart, returning a list of relevant messages """

        # these two int() conversions are safe because all the input was found to be valid
        CSIN = int(self.CSIN)
        quantity = int(self.quantity)
        
        memcache_replace = False; # true if we need to do a memcache replace instead of add (if we're updating instead of creating this cart)
        entries = [] # this assignment is only here for scope
        cartEntry = None
        item = Item.gql('WHERE CSIN = :1', CSIN).get()
        if self.user:
            cartEntry = InCart.gql("WHERE item = :1 AND owner = :2", item, self.user).get()
        else:
            cart = memcache.get(self.anon_key)
            if cart:
                cartEntry = filter(lambda x: x.item.CSIN == item.CSIN, cart)
                if len(cartEntry) == 1:
                    cartEntry = cartEntry[0]
                    cart.remove(cartEntry) # remove cartEntry so we can re-add it later
                memcache_replace = True
                entries = cart
        
        
        if cartEntry:
            cartEntry.quantity += quantity
        else:
            cartEntry = InCart(item=item, quantity=quantity) # current user is automatically added
        
        if self.user:        
            cartEntry.put()
        else:
            entries.append(cartEntry)
            if memcache_replace:
                if not memcache.replace(self.anon_key, entries, anon_timeout):
                    return ["Memcache replace failed"]
            else:
                if not memcache.add(self.anon_key, entries, anon_timeout):
                    return ["Memcache add failed"]
            
        return ['%d of item %s added to cart.' % (quantity, item.name)]
        
    def validateInput(self):
        errors = []
        try:
            int(self.CSIN)
            item = Item.gql('WHERE CSIN = :1', self.CSIN).get()
        except ValueError:
            errors.append('No valid CSIN specified.')
            
        try:
            quantity = int(self.quantity)
            if quantity < 0:
                errors.append('Quantity to add must be greater than 0.')
            if item and item.quantity < quantity:
                errors.append('Quantity of item %d (%s) requested is more than is currently in stock.' % \
                              (item.CSIN, item.name))
        except ValueError:
            errors.append('No valid quantity to add specified.')
            
        if not self.user and not self.anon_key:
            return ["No user is logged in, but no anonymous cart key was specified"]
        
        return errors
